class SessionsController < ApplicationController
  layout 'base.html'
  
  def remember_current_url_as_http_referer
  end

  def authorize
      
  end
  
  def new
    @http_referer = params[:http_referer].present? ? params[:http_referer] : request.referer
    @http_referer = nil if @http_referer.try(:match,'/homes/default')
    @session = {}
    def @session.nick_name_or_email_or_mobile      
    end
    def @session.password
    end
    def @session.remember_me
      'no'
    end
  end

  def create
    @http_referer = params[:http_referer] if params[:http_referer].present?
    if User.authenticate(params[:session][:nick_name_or_email_or_mobile],params[:session][:password])
      session[:current_user_id] = User.find_by_nick_name_or_email_or_mobile(params[:session][:nick_name_or_email_or_mobile]).id
      # remember me
      if params[:session][:remember_me] == 'yes'
        cookies.signed[:user_id] = {
          :value => current_user_id.to_s,
          :expires => 10.years.from_now
        }
        cookies.signed[:user_security_key] = {
          :value => current_user.security_key_in_cookies,
          :expires => 10.years.from_now
        }
      else
        clear_login_info_from_cookies
      end      
      redirect_to(@http_referer || user_url(current_user))
    else
      clear_login_info_from_cookies
      @login_failed = true
      @user = User.find_by_nick_name_or_email_or_mobile(params[:session][:nick_name_or_email_or_mobile])
      @session = params[:session]
      def @session.nick_name_or_email_or_mobile
        self[:nick_name_or_email_or_mobile]
      end
      def @session.password
      end
      def @session.remember_me
        self[:remember_me]
      end      
      render :action => :new
    end
  end

  def show
    
  end

  def destroy
    session.delete :current_user_id
    clear_login_info_from_cookies
    redirect_to home_url(:default)
  end

  private
  def clear_login_info_from_cookies
    cookies.delete :user_id
    cookies.delete :user_security_key
  end
end
